package controller

import (
	"fmt"
	"gin-chat/pkg"
	"gin-chat/router/request"
	"gin-chat/router/response"
	"gin-chat/service"
	"gin-chat/util"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
)

//todo::未添加验证提示信息
//注册
func Register(c *gin.Context) {
	//注入到返回类
	app := response.Gin{C: c}
	params := &request.RegisterRequest{}
	if err := c.ShouldBindJSON(params); err != nil {
		fmt.Println(err)
		app.Response(http.StatusInternalServerError, pkg.InvalidParams, nil)
		return
	}
	//todo::密码是否符要求
	ch := make(chan int64, 1)
	go util.MistInit(ch)
	//2.注册用户
	uuid := <-ch //生成的唯一id
	err := service.Register(uuid, params)
	if err != nil {
		app.Response(http.StatusInternalServerError, pkg.RegistrationFailed, nil)
		return
	}
	app.Response(http.StatusOK, pkg.RegistrationSuccess, uuid)
}

//登录
func Login(c *gin.Context) {
	app := response.Gin{C: c}
	params := &request.LoginRequest{}
	if err := c.ShouldBindJSON(params); err != nil {
		app.Response(http.StatusInternalServerError, pkg.InvalidParams, nil)
		return
	}
	login, code := service.Login(params)
	if code != 0 {
		//登录错误
		app.Response(http.StatusInternalServerError, code, nil)
		return
	}
	session := sessions.Default(c)
	session.Set("sessionId", login.UUID)
	err := session.Save()
	fmt.Println("err===", err)
	loginResponse := &request.LoginResponse{
		UUID:      login.UUID,
		Nickname:  login.Nickname,
		AvatarURL: login.AvatarURL,
		Email:     login.Email,
	}
	app.Response(http.StatusOK, pkg.LoginSuccess, loginResponse)
}
